package com.aprointeractive.android.justwar.gcm.plugin;

//import java.io.*;
//import java.util.*;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.aprointeractive.android.justwar.gcm.GCMRegistrar;

/**
 * @author awysocki
 * 
 */

public class GCMPlugin extends CordovaPlugin {

	public static final String ME = "GCMPlugin";

	public static final String REGISTER = "register";
	public static final String UNREGISTER = "unregister";

	private static String gSenderID;

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		// TODO Auto-generated method stub
		if (REGISTER.equals(action)) {

			Log.v(ME + ":execute", "data=" + args.toString());

			try {

				JSONObject jo = new JSONObject(args.toString().substring(1,
						args.toString().length() - 1));

				Log.v(ME + ":execute", "jo=" + jo.toString());

				gSenderID = (String) jo.get("senderID");

				GCMRegistrar.register(cordova.getActivity(), gSenderID);

				Log.v(ME + ":execute", "GCMRegistrar.register called ");

				callbackContext.success(Status.OK.toString());
			} catch (JSONException e) {
				Log.e(ME, "Got JSON Exception " + e.getMessage());
				callbackContext.error(Status.JSON_EXCEPTION.toString());
			}
		} else if (UNREGISTER.equals(action)) {

			GCMRegistrar.unregister(cordova.getActivity());
			Log.v(ME + ":" + UNREGISTER, "GCMRegistrar.unregister called ");

		} else {
			callbackContext.error(Status.INVALID_ACTION.toString());
			Log.e(ME, "Invalid action : " + action);
		}
		return super.execute(action, args, callbackContext);
	}

	/**
	 * Gets the Directory listing for file, in JSON format
	 * 
	 * @param file
	 *            The file for which we want to do directory listing
	 * @return JSONObject representation of directory list. e.g
	 *         {"filename":"/sdcard"
	 *         ,"isdir":true,"children":[{"filename":"a.txt"
	 *         ,"isdir":false},{..}]}
	 * @throws JSONException
	 */

}
